/**
 * API工具类
 * API Utility Class
 */

class ApiClient {
  constructor() {
    this.baseURL = '/api';
    this.token = localStorage.getItem('auth_token');
  }

  /**
   * 设置认证令牌
   */
  setToken(token) {
    this.token = token;
    if (token) {
      localStorage.setItem('auth_token', token);
    } else {
      localStorage.removeItem('auth_token');
    }
  }

  /**
   * 获取请求头
   */
  getHeaders() {
    const headers = {
      'Content-Type': 'application/json'
    };

    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`;
    }

    return headers;
  }

  /**
   * 处理响应
   */
  async handleResponse(response) {
    let data;
    
    try {
      // 检查响应的Content-Type
      const contentType = response.headers.get('content-type');
      
      if (contentType && contentType.includes('application/json')) {
        data = await response.json();
      } else {
        // 如果不是JSON响应，获取文本内容
        const text = await response.text();
        
        // 如果是HTML内容，说明可能是错误页面
        if (text.includes('<html>') || text.includes('<!DOCTYPE')) {
          throw new Error(`服务器返回了HTML页面而不是JSON数据。状态码: ${response.status}`);
        }
        
        // 尝试解析为JSON
        try {
          data = JSON.parse(text);
        } catch (parseError) {
          throw new Error(`无法解析服务器响应: ${text.substring(0, 100)}...`);
        }
      }
    } catch (error) {
      // 如果是网络错误或解析错误
      if (error.message.includes('JSON') || error.message.includes('HTML')) {
        throw error;
      }
      
      // 其他错误，可能是网络问题
      throw new Error(`网络请求失败: ${error.message}`);
    }

    if (!response.ok) {
      // 如果是401错误，清除token并跳转到登录页
      if (response.status === 401) {
        this.setToken(null);
        window.location.href = '/';
      }
      
      // 提取错误消息
      let errorMessage = '请求失败';
      if (data && typeof data === 'object') {
        errorMessage = data.message || data.error?.message || data.error || errorMessage;
      } else if (typeof data === 'string') {
        errorMessage = data;
      }
      
      throw new Error(errorMessage);
    }

    return data;
  }

  /**
   * GET请求
   */
  async get(endpoint, params = {}) {
    const url = new URL(`${this.baseURL}${endpoint}`, window.location.origin);
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null) {
        url.searchParams.append(key, params[key]);
      }
    });

    const response = await fetch(url, {
      method: 'GET',
      headers: this.getHeaders()
    });

    return this.handleResponse(response);
  }

  /**
   * POST请求
   */
  async post(endpoint, data = {}) {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(data)
    });

    return this.handleResponse(response);
  }

  /**
   * PUT请求
   */
  async put(endpoint, data = {}) {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'PUT',
      headers: this.getHeaders(),
      body: JSON.stringify(data)
    });

    return this.handleResponse(response);
  }

  /**
   * DELETE请求
   */
  async delete(endpoint) {
    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'DELETE',
      headers: this.getHeaders()
    });

    return this.handleResponse(response);
  }

  /**
   * 文件上传请求
   */
  async upload(endpoint, formData) {
    const headers = {};
    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`;
    }

    const response = await fetch(`${this.baseURL}${endpoint}`, {
      method: 'POST',
      headers,
      body: formData
    });

    return this.handleResponse(response);
  }
}

// 创建全局API客户端实例
window.api = new ApiClient();